package leetcode.day;

import java.util.Arrays;

//640. 求解方程
public class SolveEquation {
    public static void main(String[] args) {

        System.out.println(solveEquation("2x+3x-6x=x+2"));
    }

    public static String solveEquation(String equation) {
        // x的系数
        int xC = 0;
        // 等号右边的常量
        int constan = 0;
        //控制正负号的变量
        int flag = 1;

        String[] split = equation.split("=");
        for (String equationPart : split) {
            //将-,替换为+-
            equationPart = equationPart.replaceAll("-", "+-");
            for (String s : equationPart.split("\\+")) {
                if (s.isEmpty()) {
                    continue;
                }
                if (s.contains("x")) {
                    if (s.length() == 1) {
                        //特判
                        xC += flag;
                    } else if (s.length() == 2 && s.charAt(0) == '-') {
                        xC += -flag;
                    } else {
                        xC += flag * Integer.parseInt(s.substring(0, s.length() - 1));
                    }
                } else {
                    constan += flag * Integer.parseInt(s);
                }

            }
            //变号
            flag = -flag;
        }
        if (xC == 0 && constan == 0) {
            return "Infinite solutions";
        } else if (xC == 0) {
            return "No solution";
        } else {
            //相当于最后的结果将x和常数放到了一边，等号右边等于0
            //类似  5x+30=0,  所以才乘以了一个-1
            return "x=" + (-1 * constan / xC);
        }

    }


}
